package com.ruoyi.framework.config

import com.google.code.kaptcha.text.impl.DefaultTextCreator
import java.util.*

/**
 * 验证码文本生成器
 *
 * @author ruoyi
 */
class KaptchaTextCreator : DefaultTextCreator() {
    override fun getText(): String {
        var result = 0
        val random = Random()
        val x = random.nextInt(10)
        val y = random.nextInt(10)
        val suChinese = StringBuilder()
        val randomoperands = random.nextInt(3)
        if (randomoperands == 0) {
            result = x * y
            suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(x))
            suChinese.append("*")
            suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(y))
        } else if (randomoperands == 1) {
            if (x != 0 && y % x == 0) {
                result = y / x
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(y))
                suChinese.append("/")
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(x))
            } else {
                result = x + y
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(x))
                suChinese.append("+")
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(y))
            }
        } else if (randomoperands == 2) {
            if (x >= y) {
                result = x - y
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(x))
                suChinese.append("-")
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(y))
            } else {
                result = y - x
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(y))
                suChinese.append("-")
                suChinese.append(KaptchaTextCreator.Companion.CNUMBERS.get(x))
            }
        }
        suChinese.append("=?@$result")
        return suChinese.toString()
    }

    companion object {
        private val CNUMBERS =
            "0,1,2,3,4,5,6,7,8,9,10".split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    }
}
